//
//  SRControlCenter.m
//  SecretRoom
//
//  Created by Sitdhibhong Laokok on 9/2/54 BE.
//  Copyright 2554 App Tree. All rights reserved.
//

#import "SRConnectionControlCenter.h"

#import "XMLRPCRequest.h"
#import "ASIHTTPRequest.h"
#import "XMLRPCResponse.h"

#import "FBConnect.h"

@interface SRConnectionControlCenter ()
- (void)notificationRegisterInBackground;
- (id)executedXMLRPCRequest:(XMLRPCRequest *)requestGiven error:(NSError **)error;
- (NSError *)errorWithResponse:(XMLRPCResponse *)requestedGiven;

- (void)saveUserAuthenticationInformation:(NSNotification *)userInfo;
- (void)removeAllCurrentUserCredential;

//#warning implement here from 
//- (void)proposeForNewEventToSecretRoom;
//
//- (void)eventSyncEventFromSecretRoom;
//
//- (void)tagsSyncTagsFromSecretRoom;
//
//- (void)inviteeSyncFromSecretRoom;

@end

@implementation SRConnectionControlCenter

@synthesize manageObjectContext;
@synthesize defaultDateFormatterWithInDatabase;
@synthesize facebook;
@synthesize commonsFacebookConnect = _commonsFacebookConnect;

+ (SRConnectionControlCenter *)sharedInstance 
{
    static SRConnectionControlCenter *controlCenter = nil;
    if (controlCenter == nil) {
        controlCenter = [[SRConnectionControlCenter alloc] init];
    }
    
    return controlCenter;
}

+ (NSString *)categoryStringWithCategory:(kSREventCategory)category
{
    switch (category) {
        case kSREventCategoryInbox:
            return @"Inbox";
            break;
            
        case kSREventCategoryToday:
            return @"Today";
            break;
            
        case kSREventCategorySchedule:
            return @"Schedule";
            break;
            
        case kSREventCategoryLogBook:
            return @"Log Book";
            break;
            
        case kSREventCategoryOverDue:
            return @"Overdue";
            
        default:
            return @"";
            break;
    }
}

+ (NSDateFormatter *)dateFormatterWithFormat:(kSRDateFormatter)formatterSelected
{
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    
    switch (formatterSelected) {
        case kSRDateFormatterLong:
            formatter.dateFormat = @"yyyy-MM-dd HH:mm:ss";
            break;
            
        default:
            break;
    }
    
    return [formatter autorelease];
}

- (id)init
{
    self = [super init];
    if (self) {
        retryOnTimeOut = YES;
//        self.facebook = [[Facebook alloc] initWithAppId:@"" andDelegate:self.commonsFacebookConnect];
    }
    
    return self;
}

- (id)initWithManagedObjectContext:(NSManagedObjectContext *)context
{
    if (self = [super init]) {
        self.manageObjectContext = context;
        
    }
    
    return self;
}

- (void)dealloc
{
    [manageObjectContext release];
    [defaultDateFormatterWithInDatabase release];
    [facebook release];
    [commonsFacebookConnect release];
    
    [super dealloc];
}

#pragma mark - Defined method
- (void)notificationRegister
{
    [self performSelectorInBackground:@selector(notificationRegisterInBackground) 
                           withObject:nil];
}

// Backgrond performed
- (void)notificationRegisterInBackground
{
    [[NSNotificationCenter defaultCenter] addObserver:self 
                                             selector:@selector(saveUserAuthenticationInformation:) 
                                                 name:kSRNotificationCenterNameUserAuthenticationCredentialSave
                                               object:nil];
}

- (int)numberOfEventWithCategory:(kSREventCategory)category
{
    NSFetchRequest *request = [[NSFetchRequest alloc] init];
    request.entity = [NSEntityDescription entityForName:@"Event" inManagedObjectContext:self.manageObjectContext];
    
    switch (category) {
        case kSREventCategoryInbox:
            request.predicate = [NSPredicate predicateWithFormat:@"eventTimestamp beginswith %@"];
            break;
            
        default:
            break;
    }
    
    [request release];
    
    
    return 0;
}

#pragma mark - Operation Method
- (NSDictionary *)authenticationToSecretRoomWithUsername:(NSString *)username password:(NSString *)password error:(NSError **)error
{
    NSDictionary *userDictionary = nil;
    NSLog(@"Endpoint :%@", kSRRemoteInformationXMLRPCEndpointURL);
    XMLRPCRequest *xmlrpc = [[XMLRPCRequest alloc] initWithURL:[NSURL URLWithString:kSRRemoteInformationXMLRPCEndpointURL]];
    [xmlrpc setMethod:kSRRemoteInformationXMLRPCAPIsMethodUserAuthentication withParameters:[NSArray arrayWithObjects:username, password, nil]];
    retryOnTimeOut = YES;
    
    NSArray *userData = [self executedXMLRPCRequest:xmlrpc error:error];
    [xmlrpc release];
    
    if ([userData isKindOfClass:[NSDictionary class]]) {
        userDictionary = [[NSDictionary alloc] initWithDictionary:(NSDictionary *) userData];
    }
    
    return (userDictionary != nil) ? [userDictionary autorelease] : nil ;
}

- (NSString *)createNewEvent:(Event *)event error:(NSError **)error
{
    NSString *remoteEventLink = nil;
    
    return remoteEventLink;
}

#pragma mark - Secret Event 
- (id)executedXMLRPCRequest:(XMLRPCRequest *)requestedGiven error:(NSError **)error
{
    ASIHTTPRequest *request = [[ASIHTTPRequest alloc] initWithURL:[requestedGiven URL]];
    request.requestMethod = @"POST";
    request.shouldPresentCredentialsBeforeChallenge = YES;
    request.shouldPresentAuthenticationDialog = YES;
    request.useKeychainPersistence = YES;
    request.validatesSecureCertificate = NO;
    request.timeOutSeconds = 5;
    
    NSString *version = [[[NSBundle mainBundle] infoDictionary] valueForKey:[NSString stringWithFormat:@"CFBundleVersion"]];
    [request addRequestHeader:@"User-Agent" value:[NSString stringWithFormat:@"sl-secretroom-iphone/%@", version]];
    
    NSString *quickPostType = [[requestedGiven request] valueForHTTPHeaderField:@"SL-Quick-Post"];
    if (quickPostType != nil) {
        [request addRequestHeader:@"SL-Quick-Post" value:quickPostType];
    }
    
    request.numberOfTimesToRetryOnTimeout = (retryOnTimeOut) ? 2 : 0 ;
    
#ifdef XMLRPC_DEBUG
//    NSLog(@"executeXMLRPC request body: %@", [requestedGiven body]);
#endif
    
    [request appendPostData:[[requestedGiven body] dataUsingEncoding:NSUTF8StringEncoding]];
    [request startSynchronous];
    
    NSError *err = [request error];
    NSLog(@"request error %@", [request error]);
    
    if (err) {
        [request release];
        [*error release];
        *error = err;
        return nil;
    }
    
    int statusCode = [request responseStatusCode];
    if (statusCode >= 404) {
        NSDictionary *userInfo = [NSDictionary dictionaryWithObjectsAndKeys:[request responseStatusMessage], NSLocalizedDescriptionKey, nil];
        [*error release];
        * error = [NSError errorWithDomain:@"net.we.secretroom.iphone" code:statusCode userInfo:userInfo];
//        [userInfo release];
        [request release];
        return nil;
    }
    
#ifdef XMLRPC_DEBUG
    NSLog(@"executedXMLRPCResponse reponse: %@", [request responseString]);
#endif
    
    XMLRPCResponse *userInfoResponse = [[[XMLRPCResponse alloc] initWithData:[request responseData]] autorelease];
    [request release];
    
    err = [self errorWithResponse:userInfoResponse];
    NSLog(@"error: %@", err);
    if (err != nil) {
        [ * error release];
        * error = err;
        return nil;
    } 
    
//    *error = nil;
    return [userInfoResponse object];
}

- (NSError *)errorWithResponse:(XMLRPCResponse *)response
{
    NSError *e = nil;
    
    if ([response isKindOfClass:[NSError class]]) {
        e = (NSError *)response;
    }
    
    return [e autorelease];
}

- (void)saveUserAuthenticationInformation:(NSNotification *)userInfo
{
    NSDictionary *userInfoDictionary = [[userInfo userInfo] objectForKey:@"userInfo"];

    if (userInfoDictionary == nil) return;
    
    
    [[NSUserDefaults standardUserDefaults] setObject:[userInfoDictionary objectForKey:@"ID"] 
                                              forKey:kSRPreferenceRemoteValueUID];
    [[NSUserDefaults standardUserDefaults] setObject:[userInfoDictionary objectForKey:@"remote_username"] 
                                              forKey:kSRPreferenceRemoteValueUsername];
    [[NSUserDefaults standardUserDefaults] setObject:[userInfoDictionary objectForKey:@"remote_password"] 
                                              forKey:kSRPreferenceRemoteValuePassword];
    [[NSUserDefaults standardUserDefaults] setObject:[userInfoDictionary objectForKey:@"user_email"] 
                                              forKey:kSRPreferenceRemoteValueEMail];
    [[NSUserDefaults standardUserDefaults] setObject:[userInfoDictionary objectForKey:@"first_name"] 
                                              forKey:kSRPreferenceRemoteValueFirstName];
    [[NSUserDefaults standardUserDefaults] setObject:[userInfoDictionary objectForKey:@"last_name"] 
                                              forKey:kSRPreferenceRemoteValueLastName];
    [[NSUserDefaults standardUserDefaults] setObject:[userInfoDictionary objectForKey:@"nickname"] 
                                              forKey:kSRPreferenceRemoteValueNickName];
    [[NSUserDefaults standardUserDefaults] setObject:[userInfoDictionary objectForKey:@"user_ssl"] 
                                              forKey:kSRPreferenceRemoteValueUserSSL];
    [[NSUserDefaults standardUserDefaults] setObject:[userInfoDictionary objectForKey:@"user_status"] 
                                              forKey:kSRPreferenceRemoteValueUserStatus];
    [[NSUserDefaults standardUserDefaults] setObject:[userInfoDictionary objectForKey:@"user_url"] 
                                              forKey:kSRPreferenceRemoteValueUserUrl];
    
    [[NSUserDefaults standardUserDefaults] synchronize];
}

- (void)removeAllCurrentUserCredential
{
    [[NSUserDefaults standardUserDefaults] setObject:nil
                                              forKey:kSRPreferenceRemoteValueUID];
    [[NSUserDefaults standardUserDefaults] setObject:@"Username" 
                                              forKey:kSRPreferenceRemoteValueUsername];
    [[NSUserDefaults standardUserDefaults] setObject:@"Password" 
                                              forKey:kSRPreferenceRemoteValuePassword];
    [[NSUserDefaults standardUserDefaults] setObject:nil 
                                              forKey:kSRPreferenceRemoteValueEMail];
    [[NSUserDefaults standardUserDefaults] setObject:nil
                                              forKey:kSRPreferenceRemoteValueFirstName];
    [[NSUserDefaults standardUserDefaults] setObject:nil
                                              forKey:kSRPreferenceRemoteValueLastName];
    [[NSUserDefaults standardUserDefaults] setObject:nil 
                                              forKey:kSRPreferenceRemoteValueNickName];
    [[NSUserDefaults standardUserDefaults] setObject:nil 
                                              forKey:kSRPreferenceRemoteValueUserSSL];
    [[NSUserDefaults standardUserDefaults] setObject:nil
                                              forKey:kSRPreferenceRemoteValueUserStatus];
    [[NSUserDefaults standardUserDefaults] setObject:nil
                                              forKey:kSRPreferenceRemoteValueUserUrl];
    
    [[NSUserDefaults standardUserDefaults] synchronize];
    
    NSFetchRequest *request = [[NSFetchRequest alloc] init];
    request.entity = [NSEntityDescription entityForName:@"Tag" inManagedObjectContext:self.manageObjectContext];
    
    NSArray *tagList = [self.manageObjectContext executeFetchRequest:request error:nil];
    for (NSManagedObject *o in tagList) {
        [self.manageObjectContext deleteObject:o];
    }
    
    request.entity = [NSEntityDescription entityForName:@"Invitees" inManagedObjectContext:self.manageObjectContext];
    NSArray *invitees = [self.manageObjectContext executeFetchRequest:request error:nil];
    for (NSManagedObject *o in invitees) {
        [self.manageObjectContext deleteObject:o];
    }
    
    request.entity = [NSEntityDescription entityForName:@"EvidenceMeta" inManagedObjectContext:self.manageObjectContext];
    NSArray *metaList = [self.manageObjectContext executeFetchRequest:request error:nil];
    for (NSManagedObject *o in metaList) {
        [self.manageObjectContext deleteObject:o];
    }
    
    request.entity = [NSEntityDescription entityForName:@"Evidence" inManagedObjectContext:self.manageObjectContext];
    NSArray *evidenceList = [self.manageObjectContext executeFetchRequest:request error:nil];
    for (NSManagedObject *o in evidenceList) {
        [self.manageObjectContext deleteObject:o];
    }
    
    request.entity = [NSEntityDescription entityForName:@"Event" inManagedObjectContext:self.manageObjectContext];
    NSArray *events = [self.manageObjectContext executeFetchRequest:request error:nil];
    for (NSManagedObject *o in events) {
        [self.manageObjectContext deleteObject:o];
    }
    
    [request release];
    
    [self.manageObjectContext save:nil];
}

- (SLCommonsFacebookConnect *)commonsFacebookConnect
{
    if (_commonsFacebookConnect != nil) {
        return _commonsFacebookConnect;
    }
    
    SLCommonsFacebookConnect *fc = [[SLCommonsFacebookConnect alloc] init];
    self.commonsFacebookConnect = fc;
    [fc release];
    
    return _commonsFacebookConnect;
}

@end
